import { formKeyLanguageSuffixOptions } from '#/config/options/locales'
import { getOptionsLabelByValue } from '#/config/options/utils'
import { $t } from '@vben/locales'
import { preferences } from '@vben/preferences'
import { computed } from 'vue'

// 数组转json
export function rebuildZStructure(
    items: Record<string, any>[],
    opts?: { labelKey: string; valueKey: string }
): Record<string, any> {
    const result: Record<string, any> = {}

    const { labelKey = 'label', valueKey = 'value' } = opts || {}

    for (const item of items) {
        // 清理路径并分割为键数组
        const keys = item[valueKey].replaceAll("'", '').split('.')
        let current = result

        for (let i = 0; i < keys.length; i++) {
            const key = keys[i] as string
            const isLast = i === keys.length - 1

            if (isLast) {
                // 设置最终值
                current[key] = item[labelKey]
            } else {
                // 确保当前层级存在且是对象
                if (!current[key]) {
                    current[key] = {}
                }

                current = current[key]
            }
        }
    }

    return result
}

export function generateMenuTree(
    data: Record<string, any>,
    opts?: { isNeedLocaleLabel?: boolean; prefix?: string }
) {
    const { isNeedLocaleLabel = true, prefix = '' } = opts || {}
    const buildTree = (currentData: any, path = '') => {
        const tree: any[] = []

        for (const key in currentData) {
            const node = currentData[key]

            const currentPath = path ? `${path}.${key}` : key

            if (typeof node === 'object' && node.title && node.children) {
                const value = `${prefix}${currentPath}.title`

                // 处理带标题的父节点
                tree.push({
                    label: isNeedLocaleLabel
                        ? $t(value)
                        : typeof node === 'object'
                          ? node.title
                          : node,
                    value,
                    children: buildTree(node.children, `${currentPath}.children`)
                })
            } else if (typeof node === 'object') {
                // 处理子节点对象（无title的情况）
                tree.push(...buildTree(node, currentPath))
            } else {
                const value = `${prefix}${currentPath}`
                // 处理叶子节点
                tree.push({
                    label: isNeedLocaleLabel
                        ? $t(value)
                        : typeof node === 'object'
                          ? node.title
                          : node,
                    value
                })
            }
        }

        return tree
    }

    return buildTree(data)
}

const modules = import.meta.glob('/src/locales/langs/zh-CN/**/*.json', { eager: true })

// 本地语言配置
const locales: Record<string, any> = {}

// 处理导入的 JSON 数据，使用文件名作为 key
for (const path in modules) {
    const filename = path.split('/').pop()?.replace('.json', '') // 提取文件名
    if (filename) {
        locales[filename] = (modules[path] as any).default
    }
}

// 国际化配置json
export const localesJSONConfig = locales

// 菜单国际化配置
export const localesMenuOptions = computed(() => {
    return generateMenuTree(locales.menu, {
        prefix: 'menu.'
    })
})

// 本地语言转树结构
export function toLocalesTreeOptions(locales: Record<string, any>) {
    const localesTreeOptionsMapKey = [
        { label: '通用', value: 'common' },
        { label: '菜单', value: 'menu' },
        { label: '页面', value: 'page' },
        { label: 'UI', value: 'ui' },
        { label: '登录/认证相关', value: 'authentication' },
        { label: '选项', value: 'options' },
        { label: '组件', value: 'components' },
        { label: '其他', value: 'hook' },
        { label: '创作者端', value: 'creatorTerminal' }
    ]

    type TreeDataItem = {
        [key: string]: any
        children?: TreeDataItem[]
        key: string
        label: string
        value: string
    }

    const arr: TreeDataItem[] = []

    Object.keys(locales)
        // 排序
        .sort((a, b) => {
            return (
                localesTreeOptionsMapKey.findIndex((item) => item.value === a) -
                localesTreeOptionsMapKey.findIndex((item) => item.value === b)
            )
        })
        .forEach((key) => {
            const keyLocale = getOptionsLabelByValue(key, localesTreeOptionsMapKey) as string
            arr.push({
                label: keyLocale || key,
                value: key,
                key,
                children: generateMenuTree(locales[key], {
                    prefix: `${key}.`,
                    isNeedLocaleLabel: false
                })
            })
        })
    return arr
}

// 国际化配置 树结构
export const localesTreeOptions = computed(() => {
    return toLocalesTreeOptions(locales)
})

/**
 * 根据语言获取对应的表单可以 如 nameEn nameZh
 * @param prefix 表单字段前缀
 * @returns
 */
export const getFormkeyByLocale = (prefix: string) => {
    return (
        prefix +
        (getOptionsLabelByValue(preferences.app.locale, formKeyLanguageSuffixOptions) || '')
    )
}
